//
//  PK-ios
//
//  Created by Seven on 15/9/15.
//  Copyright (c) 2015年 Seven. All rights reserved.
//

#import "UIView+Category.h"
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h>
#import "NSObject+category.h"

#define ANGLE_TO_RADIAN(angle) ((angle)/180.0* M_PI)
#define kToRadian(A) (A/360.0 * (M_PI * 2))

@implementation UIView (Category)

#pragma mark - customIndexKey
const NSString *customIndexKey = @"customIndexKey";
- (void)setCustomIndex:(NSInteger)customIndex{
    objc_setAssociatedObject(self, (__bridge const void *)(customIndexKey), @(customIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSInteger)customIndex{
    NSNumber *tmp = objc_getAssociatedObject(self, (__bridge const void *)(customIndexKey));
    return [tmp integerValue];
}


+ (instancetype)initWithFrame:(CGRect)frame{
    
    UIView *tmp = [[self alloc] initWithFrame:frame];
    return tmp;
}

- (void)initViews{}

- (void)appendBorderLine:(int)direction width:(float)w color:(UIColor*)c
{
    CGRect rect = CGRectZero;
    if (0==direction) {//上
        rect = CGRectMake(0, 0, self.width, w);
    }
    else if (1==direction) {//左
        rect = CGRectMake(0, 0, w, self.height);
    }
    else if (2==direction) {//下
        rect = CGRectMake(0, self.height-w, self.width, w);
    }
    else if (3==direction) {//右
        rect = CGRectMake(self.width-w, 0, w, self.height);
    }
    
    [self.layer addSublayer:[CALayer lineWithFrame:rect color:c]];
}

- (void)addLineWithFrame:(CGRect)frame{
    [self.layer addSublayer:[CALayer lineWithFrame:frame color:nil]];
}
- (void)addLineWithFrame:(CGRect)frame color:(UIColor *)c{
    [self.layer addSublayer:[CALayer lineWithFrame:frame color:c]];
}

+ (instancetype)lineWithFrame:(CGRect)frame color:(UIColor *)c{
    UIView *line = [UIView initWithFrame:frame];
    line.backgroundColor = c ?: [UIColor hexStringColor:@"dddddd"];
    line.userInteractionEnabled = NO;
    return line;
}
+ (instancetype)lineView{
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor hexStringColor:@"dddddd"];
    line.userInteractionEnabled = NO;
    line.height = .5;
    return line;
}


- (CAGradientLayer *)gradientColorWithStartPoint:(CGPoint)startPoint toPoint:(CGPoint)toPoint fromColor:(UIColor *)fromColor toColor:(UIColor *)toColor locations:(NSArray *)locations{
    CAGradientLayer *gradientLayer = [CAGradientLayer gradientColorWithStartPoint:startPoint toPoint:toPoint fromColor:fromColor toColor:toColor locations:locations];
    gradientLayer.frame = self.bounds;
    [self.layer insertSublayer:gradientLayer atIndex:0];
    return gradientLayer;
}

- (CAGradientLayer *)gradientColorWithStartPoint:(CGPoint)startPoint toPoint:(CGPoint)toPoint colors:(NSArray *)colors locations:(NSArray *)locations{
    CAGradientLayer *gradientLayer = [CAGradientLayer gradientColorWithStartPoint:startPoint toPoint:toPoint colors:colors locations:locations];
    gradientLayer.frame = self.bounds;
    [self.layer insertSublayer:gradientLayer atIndex:0];
    return gradientLayer;
}

@end
@implementation UIView (Screenshot)

- (UIImage*) screenshot {
    return [self screenshotScale:0.75];
    
}

-(UIImage *)screenshotScale:(CGFloat)scale{
    if (scale < 0) {
        scale = 0.1;
    }
    if (scale > 1) {
        scale = 1;
    }
    
//    UIGraphicsBeginImageContext(self.bounds.size);
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // helps w/ our colors when blurring
    // feel free to adjust jpeg quality (lower = higher perf)
//    NSData *imageData = UIImageJPEGRepresentation(image, scale);
    NSData *imageData = UIImagePNGRepresentation(image);
    image = [UIImage imageWithData:imageData];
    
    return image;
}

- (UIImage *) screenshotForScrollViewWithContentOffset:(CGPoint)contentOffset {
    UIGraphicsBeginImageContext(self.bounds.size);
    //need to translate the context down to the current visible portion of the scrollview
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0f, -contentOffset.y);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // helps w/ our colors when blurring
    // feel free to adjust jpeg quality (lower = higher perf)
    NSData *imageData = UIImageJPEGRepresentation(image, 0.55);
    image = [UIImage imageWithData:imageData];
    
    return image;
}

- (UIImage*) screenshotInFrame:(CGRect)frame {
    UIGraphicsBeginImageContext(frame.size);
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), frame.origin.x, frame.origin.y);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // helps w/ our colors when blurring
    // feel free to adjust jpeg quality (lower = higher perf)
    NSData *imageData = UIImageJPEGRepresentation(image, 0.75);
    image = [UIImage imageWithData:imageData];
    
    return image;
}

@end

@implementation UIView (Animation)

- (void)moveAnimation{
    CALayer* layer = [self layer];
    CGPoint p = layer.position;
    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"position.y"];
    [animation setTimingFunction:[CAMediaTimingFunction
                                  functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:@(p.y)];
    [animation setToValue:@(p.y+10)];
    [animation setAutoreverses:YES];
    [animation setDuration:1];
    animation.repeatCount=NSIntegerMax;
    [layer addAnimation:animation forKey:nil];
}

- (void) shakeAnimation2 {

    CALayer* layer = [self layer];
    CGPoint position = [layer position];
    CGPoint y = CGPointMake(position.x - 8.0f, position.y);
    CGPoint x = CGPointMake(position.x + 8.0f, position.y);
    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction
                                  functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    [animation setAutoreverses:YES];
    [animation setDuration:0.08f];
    [animation setRepeatCount:3];
    [layer addAnimation:animation forKey:nil];
}


- (void)shakeAnimation{
    //实例化

    CAKeyframeAnimation*anim = [CAKeyframeAnimation animation];
    //拿到动画key
    anim.keyPath=@"transform.rotation.z";
    //动画时间
    anim.duration=.2;
    //重复的次数
    //anim.repeatCount = 16;
    //无限次重复
    anim.repeatCount=NSIntegerMax;

    //设置抖动数值
    //anim.values = @[@(ANGLE_TO_RADIAN(-5)),@(ANGLE_TO_RADIAN(5)),@(ANGLE_TO_RADIAN(-5))];
    anim.values = @[@(kToRadian(5)),@(kToRadian(0)),@(kToRadian(-5)),@(kToRadian(0)),@(kToRadian(5))];

    //layer层实现动画
    [self.layer addAnimation:anim forKey:@"shake"];
}

- (void) trans180DegreeAnimation
{
    [UIView animateWithDuration:0.3 animations:^{
        self.layer.transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);
    }];
}

- (void)praiseAnimation
{
    CAKeyframeAnimation *praiseAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    praiseAnimation.values = @[@(0.5),@(1.0)];
    praiseAnimation.keyTimes = @[@(0.0),@(0.5),@(0.8),@(1.0)];
    praiseAnimation.calculationMode = kCAAnimationLinear;
    [self.layer addAnimation:praiseAnimation forKey:@"praiseAnimation"];
}

- (void)springingAnimation
{
    CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = 0.4;
    popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.2f, @0.5f, @0.75f, @1.0f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [[self layer] addAnimation:popAnimation forKey:nil];
}

- (void)scaleAnimation{
    [self scaleAnimation:0.9];
}

- (void)scaleAnimation:(CGFloat)scale{
    [self.layer removeAnimationForKey:@"scaleAnimation"];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation.fromValue = @(1);
    animation.toValue = @(scale);
    animation.duration  =  1;
    animation.autoreverses = YES;
    animation.cumulative = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = NSUIntegerMax;
    [self.layer addAnimation:animation forKey:@"scaleAnimation"];
}

- (void)rotateAnimation{
    [self.layer removeAnimationForKey:@"rotateAnimation"];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = @(0);
    animation.toValue = @(2.0 * M_PI);
    animation.duration  =  3.3;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = NSUIntegerMax;
    [self.layer addAnimation:animation forKey:@"rotateAnimation"];
}


- (void) rotateAnimationY{
    [self.layer removeAnimationForKey:@"rotateAnimationY"];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];
    animation.fromValue = @(0);
    animation.toValue = @(M_PI*2);
    animation.duration  =  0.3;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.fillMode = kCAFillModeForwards;
    //animation.repeatCount = NSUIntegerMax;
    [self.layer addAnimation:animation forKey:@"rotateAnimationY"];
}

- (void)fadeAnimation
{
    CATransition *transition = [[CATransition alloc] init];
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.duration = 0.2;
    transition.type = kCATransitionFade;
    [self.layer addAnimation:transition forKey:@"fadeAnimation"];
}

- (void)pushAnimation{
    CATransition *transition=[[CATransition alloc]init];
    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromTop;
    transition.duration = 0.3;
    [self.layer addAnimation:transition forKey:nil];
}

- (void)popAnimation{
    CATransition *transition=[[CATransition alloc]init];
    transition.type = kCATransitionReveal;
    transition.subtype = kCATransitionFromBottom;
    transition.duration = 0.3;
    [self.layer addAnimation:transition forKey:nil];
}


- (void)startLikeAnimationWithAppearanceConfig:(void (^)(void))config completion:(void (^)(void))completion {
    
    [UIView animateWithDuration:0.2 delay:0  options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
        self.layer.transform = CATransform3DMakeScale(1.1, 1.1, 0); // 放大
    } completion:^(BOOL finished) {
        
        // 截图、淡出
//        UIImage *snapshot = [self snapshotImage];
//        UIImageView *imageView = [[UIImageView alloc] initWithImage:snapshot];
//        imageView.size = snapshot.size;
//        imageView.center = self.center;
//        imageView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.2, 1.2);
//        [self.superview addSubview:imageView];
//        [imageView startFadeAwayAnimationWithCompletion:^{
//            [imageView removeFromSuperview];
//        }];
        
        // 改变外观
        if (config) {
            config();
        }
        
        [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
            self.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0);// 缩小
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.15 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
                self.layer.transform = CATransform3DMakeScale(1.05, 1.05, 0);// 放大
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
                    self.layer.transform = CATransform3DIdentity;  // 还原
                } completion:^(BOOL finished) {
                    if (completion) {
                        completion();
                    }
                }];
            }];
        }];
    }];
    
}

// 暂停动画

- (void)pauseAnimation
{
    
    [self.layer pauseAnimation];
    
}

// 恢复动画

- (void)resumeAnimation
{
    [self.layer resumeAnimation];
}


@end


@implementation UIView (Corner)

-(void)setCurrentShapeLayer:(CAShapeLayer *)currentShapeLayer
{
    [self objc_setAssociatedObject:@"currentShapeLayer" value:currentShapeLayer policy:OBJC_ASSOCIATION_RETAIN_NONATOMIC];
}

-(CAShapeLayer*)currentShapeLayer
{
    return [self objc_getAssociatedObject:@"currentShapeLayer"];
}

//添加四周圆角
- (void)addAllCornerWithSize:(CGSize)aSize
{
    [self addCornerWithType:UIRectCornerAllCorners size:aSize borderColor:nil borderWidth:0];
}

//添加位置方向的圆角
- (void)addCornerWithType:(UIRectCorner)aCorners size:(CGSize)aSize
{
    [self addCornerWithType:aCorners size:aSize borderColor:nil borderWidth:0];
}


-(void)addCornerWithType:(UIRectCorner)aCorners size:(CGSize)aSize borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:aCorners cornerRadii:aSize];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
    
    if (borderColor && borderWidth>0) {
        //由于mask忽略颜色属性，所以如果要加线框，必须重新画新的线
        [self.currentShapeLayer removeFromSuperlayer];
        CAShapeLayer *borderLayer=[CAShapeLayer layer];
        borderLayer.path        = maskPath.CGPath;
        borderLayer.fillColor   = [UIColor clearColor].CGColor;
        borderLayer.strokeColor = borderColor.CGColor;
        borderLayer.lineWidth   = borderWidth;
        borderLayer.frame       = self.bounds;
        [self.layer addSublayer:borderLayer];
        self.currentShapeLayer=borderLayer;
    }
    self.layer.shouldRasterize = YES;
    self.layer.rasterizationScale = [UIScreen mainScreen].scale;
}

-(UIImage *)convertToImage {
    
    CGSize viewSize = self.bounds.size;
    UIGraphicsBeginImageContextWithOptions(viewSize, NO, [UIScreen mainScreen].scale);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (nullable NSArray *)calculateFourPointsInRateStyle {
    if (self.superview) {
        CGPoint centerPoint = self.center;
        CGFloat diagonalLenth = sqrt(pow(self.bounds.size.width, 2) + pow(self.bounds.size.height, 2));
        
        //对角线角度
        CGFloat diagonalRotate = acosf(self.bounds.size.width/diagonalLenth);
        //        CGFloat diagonalDegree = acosf(view.bounds.size.width/diagonalLenth)/M_PI * 180;
        
        //旋转角度
        CGAffineTransform _trans = self.transform;
        CGFloat rotate = acosf(_trans.a);
        if (_trans.b < 0) {
            rotate = 2 * M_PI -rotate;
        }
        //        CGFloat degree = rotate/M_PI * 180;
        
        CGFloat offsetX = cosf(rotate + diagonalRotate) * diagonalLenth/2;
        CGFloat offsetY = sinf(rotate + diagonalRotate) * diagonalLenth/2;
        
        CGPoint pointTopLeft = CGPointMake(centerPoint.x - offsetX, centerPoint.y - offsetY);
        
        
        CGPoint pointBottomRight = CGPointMake(centerPoint.x + offsetX, centerPoint.y + offsetY);
        
        
        
        offsetX = cosf(diagonalRotate - rotate) * diagonalLenth/2;
        offsetY = sinf(diagonalRotate - rotate) * diagonalLenth/2;
        
        CGPoint pointTopRight = CGPointMake(centerPoint.x + offsetX, centerPoint.y - offsetY);
        
        
        CGPoint pointBottomLeft = CGPointMake(centerPoint.x - offsetX, centerPoint.y + offsetY);
        
        
        NSLog(@"%@ %@ %@ %@", NSStringFromCGPoint(pointTopLeft), NSStringFromCGPoint(pointTopRight), NSStringFromCGPoint(pointBottomLeft),
              NSStringFromCGPoint(pointBottomRight));
        
        
        CGPoint pointTopLeftRate = CGPointMake(pointTopLeft.x/self.superview.frame.size.width, pointTopLeft.y/self.superview.frame.size.height);
        
        CGPoint pointBottomRightRate = CGPointMake(pointBottomRight.x/self.superview.frame.size.width, pointBottomRight.y/self.superview.frame.size.height);
        
        CGPoint pointTopRightRate = CGPointMake(pointTopRight.x/self.superview.frame.size.width, pointTopRight.y/self.superview.frame.size.height);
        
        CGPoint pointBottomLeftRate = CGPointMake(pointBottomLeft.x/self.superview.frame.size.width, pointBottomLeft.y/self.superview.frame.size.height);
        
        NSString *pointTopLeftRateString = NSStringFromCGPoint(pointTopLeftRate);
        NSString *pointBottomRightRateString = NSStringFromCGPoint(pointBottomRightRate);
        NSString *pointTopRightRateString = NSStringFromCGPoint(pointTopRightRate);
        NSString *pointBottomLeftString = NSStringFromCGPoint(pointBottomLeftRate);
        
        NSLog(@"%@ %@ %@ %@", pointTopLeftRateString, pointTopRightRateString, pointBottomRightRateString,
              pointBottomLeftString);
        
        NSArray *array = @[pointTopLeftRateString, pointTopRightRateString, pointBottomLeftString, pointBottomRightRateString];
        return array;
    } else {
        return nil;
    }
}

@end


@implementation CALayer(extension)
//lineView
+ (instancetype)lineWithFrame:(CGRect)frame color:(UIColor *)color{
    CALayer *lineLayer = [[CALayer alloc] init];
    lineLayer.frame = frame;
    lineLayer.backgroundColor = color.CGColor ?: [UIColor hexStringColor:@"dddddd"].CGColor;
    return lineLayer;
}

//Corners
+ (id)maskLayerWithCorners:(UIRectCorner)corners radii:(CGSize)radii frame:(CGRect)frame {
    
    // Create a CAShapeLayer
    CAShapeLayer *mask = [CAShapeLayer layer];
    
    // Set the frame
    mask.frame = frame;
    
    // Set the CGPath from a UIBezierPath
    mask.path = [UIBezierPath bezierPathWithRoundedRect:mask.bounds byRoundingCorners:corners cornerRadii:radii].CGPath;
    
    // Set the fill color
    mask.fillColor = [UIColor whiteColor].CGColor;
    
    return mask;
}


+ (CAGradientLayer *)gradientColorWithStartPoint:(CGPoint)startPoint toPoint:(CGPoint)toPoint fromColor:(UIColor *)fromColor toColor:(UIColor *)toColor locations:(NSArray *)locations{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    //gradientLayer.frame = self.bounds;
    //[self.layer insertSublayer:gradientLayer atIndex:0];
    
    //    gradientLayer.startPoint = CGPointMake(0, 0);
    //    gradientLayer.endPoint = CGPointMake(1, 0.6);
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = toPoint;
    gradientLayer.colors = @[(__bridge id)fromColor.CGColor,
                             (__bridge id)toColor.CGColor];
    gradientLayer.locations = locations;
    return gradientLayer;
}

+ (CAGradientLayer *)gradientColorWithStartPoint:(CGPoint)startPoint toPoint:(CGPoint)toPoint colors:(NSArray *)colors locations:(NSArray *)locations{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    //gradientLayer.frame = self.bounds;
    //[self.layer insertSublayer:gradientLayer atIndex:0];
    //    gradientLayer.startPoint = CGPointMake(0, 0);
    //    gradientLayer.endPoint = CGPointMake(1, 0.6);
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = toPoint;
    NSMutableArray *tmp = NSMutableArray.array;
    [colors enumerateObjectsUsingBlock:^(UIColor *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:UIColor.class]) {
            [tmp addObject:(id)obj.CGColor];
        }else {
            [tmp addObject:obj];
        }
    }];
    gradientLayer.colors = tmp;
    gradientLayer.locations = locations;
    return gradientLayer;
}

+ (CALayer *)layerWithImage:(id)image frame:(CGRect)frame{
    CALayer *icon = CALayer.layer;
    icon.frame = frame;
    icon.contentMode = UIViewContentModeCenter;
    UIImage *img = nil;
    if ([image isKindOfClass:UIImage.class]) {
        img = image;
    }else if ([image isKindOfClass:NSString.class]){
        img = [UIImage imageNamed:image];
    }
    icon.contents = (id)img.CGImage;
    icon.contentsScale = UIScreen.mainScreen.scale;
    return icon;
}

// 暂停动画

- (void)pauseAnimation
{
    // 取出当前的时间点，就是暂停的时间点
    CFTimeInterval pausetime = [self convertTime:CACurrentMediaTime() fromLayer:nil];
    
    // 设定时间偏移量，让动画定格在那个时间点
    [self setTimeOffset:pausetime];
    
    // 将速度设为0
    [self setSpeed:0.0f];
    
}

// 恢复动画

- (void)resumeAnimation
{
    // 获取暂停的时间
    CFTimeInterval pausetime = self.timeOffset;
    if (pausetime > 0) {
        // 计算出此次播放时间(从暂停到现在，相隔了多久时间)
        CFTimeInterval starttime = CACurrentMediaTime() - pausetime;
        
        // 将时间偏移量设为0(重新开始)；
        self.timeOffset = 0.0;
        
        // 设置开始时间(beginTime是相对于父级对象的开始时间,系统会根据时间间隔帮我们算出什么时候开始动画)
        self.beginTime = starttime;
        
        // 将速度恢复，设为1
        self.speed = 1.0;
    }
}



@end


@implementation UIView(loading)

- (MBProgressHUD *)showLoading{
    return [self showLoadingWithTitle:@""];
}

- (MBProgressHUD *)showLoadingWithTitle:(NSString *)title{
    //提示成功
    UIView *appRootView = self;
    MBProgressHUD *newhud = (MBProgressHUD *)[appRootView viewWithTag:MBProgressGIFTAG];
    if (newhud == nil) {
        newhud = [[MBProgressHUD alloc] initWithView:appRootView];
        newhud.tag = MBProgressGIFTAG;
        //newhud.userInteractionEnabled = NO;
        [newhud.bezelView setStyle:MBProgressHUDBackgroundStyleSolidColor];
        newhud.bezelView.backgroundColor = [UIColor whiteColor];//这儿表示无背景
        /*!
         *  @author WS, 15-11-26 15:11:52
         *
         *  是否显示遮罩
         */
        newhud.backgroundColor = [UIColor clearColor];
        newhud.backgroundView.backgroundColor = [UIColor clearColor];
        /*!
         *  @author WS, 15-11-26 15:11:05
         *
         *  字体颜色
         */
        newhud.label.textColor=[UIColor blackColor];
        
        newhud.mode = MBProgressHUDModeCustomView;
        
        /*!
         *  @author WS, 15-11-26 15:11:32
         *
         *  如果修改动画图片就在这里修改
         */
    
        YYImage *image=[YYImage imageNamed:@"RefreshHead"];
        newhud.customView = [[YYAnimatedImageView alloc] initWithImage:image];
    }
    
    newhud.label.text = title;
    
    [newhud showAnimated:YES];

    [appRootView addSubview:newhud];
    newhud.center = CGPointMake(appRootView.width/2, appRootView.height/2);
    return newhud;
}


- (void)hideLoading{
    [self hideLoading:YES];
}

- (void)hideLoading:(BOOL)animation{
    UIView *appRootView = self;
    for (MBProgressHUD *hud in appRootView.subviews) {
        if (hud.tag == MBProgressGIFTAG) {
            if ([hud isKindOfClass:MBProgressHUD.class]) {
                hud.removeFromSuperViewOnHide = YES;
                [hud hideAnimated:animation];
            }else {
                
            }
        }
    }
}


- (void)showInfo:(NSString *)text{
    [self hideToast];
    [self showInfo:text position:nil];
}

- (void)showInfo:(NSString *)text position:(id)position{
    [self makeToast:text duration:2 position:position];
}

@end
